<?php
/**
 * 公共的Model
 *
 * @author zwg
 * 
 */
class MY_Model extends CI_Model
{
    protected $_table_name = '';
    protected $_id = 'id';
    
    
    public function set_table($table_name, $id = 'id'){
        $this->_table_name = $table_name;
        $this->_id = $id;
    }
    
    public function table_exists($table_name){
    	return $this->db->table_exists($table_name);
    }

    public function find($id, $select = '*'){
        $this->db->select($select);
        $this->db->where($this->_id, $id);
        return $this->db->get($this->_table_name)->row_array();
    }
    
    public function flush(){
    	$this->db->flush_cache();
    }

    public function find_one($where, $select = '*'){
        $this->db->select($select);
        $this->db->where($where);
        return $this->db->get($this->_table_name)->row_array();
    }

    public function delete($id){
        $this->db->where($this->_id, $id);
        return $this->db->delete($this->_table_name)?TRUE:FALSE;
    }

    public function insert($new_data){
    	if($this->db->insert($this->_table_name, $new_data)){
    		$new_id = $this->db->insert_id();
    		if($new_id){
    			return $new_id;
    		}
    		return true;
    	}else{
    		return false;
    	}
        //return $this->db->insert($this->_table_name, $new_data)?TRUE:FALSE;
    }
    
    public function insert_batch($new_data){
    	//log_message('info', $this->db->inser($this->_table_name, $new_data));
        return $this->db->insert_batch($this->_table_name, $new_data)?TRUE:FALSE;
    }

    public function update($new_data, $id = 0){
        $this->db->where($this->_id, $id);
        return $this->db->update($this->_table_name, $new_data)?TRUE:FALSE;
    }
    public function updateByWhere($where,$values){
    	$this->db->where($where);
    	return $this->db->update($this->_table_name, $values)?TRUE:FALSE;
    }
    /**
     * return affected_rows
     */
    public function update_rows($new_data, $id = 0){
        $this->db->where($this->_id, $id);
        $this->db->update($this->_table_name, $new_data);
        return $this->db->affected_rows();
    }

    public function get($where=NULL,$page=1,$page_size=100,$select='*',$orderby=NULL){
        $this->db->limit($page_size, $page_size * ($page - 1));

        isset($select) && $this->db->select($select);
        isset($where) && !empty($where) && $this->db->where($where);
        if(isset($orderby)){
        	if(is_array($orderby)){
        		foreach ( $orderby as $key => $value ) {
				      $this->db->order_by($key,$value); 
				}
        	}else if(is_string($orderby)){
        		$this->db->order_by($orderby); 
        	}
        }
        
        return $this->db->get($this->_table_name)->result_array();
    }
    
    
    public function count($where=NULL){
    	isset($where) && !empty($where) && $this->db->where($where);
    	return $this->db->count_all_results($this->_table_name);    	
    }
}
